//
//  AllListViewController.m
//  YoucApp
//
//  Created by Liam on 11/25/12.
//
//

#import "AllListViewController.h"
#import "AttentionManager.h"
#import "YAObjGame.h"
#import "ListManager.h"
#import "SearchBarWithActivity.h"

@interface AllListViewController ()

@property (retain, nonatomic) SearchBarWithActivity *searchBar;
@property (assign, nonatomic) BOOL isSearching;
@property (retain, nonatomic) NSArray *searchGameList;
@property (retain, nonatomic) NSArray *tmpGameList;

@end

@implementation AllListViewController

@synthesize searchBar = _searchBar;
@synthesize isSearching = _isSearching;
@synthesize searchGameList = _searchGameList;
@synthesize tmpGameList = _tmpGameList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	
	self.searchBar = [[[SearchBarWithActivity alloc] initWithFrame:CGRectZero] autorelease];
	self.searchBar.delegate = self;
	
	[self createRefreshFooter];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAttentionNotication:) name:AMAddAttentionNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAttentionNotication:) name:AMDeleteAttentionNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchGamesNotification:) name:LMSearchGamesDidFinishedNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:AMAddAttentionNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:AMDeleteAttentionNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:LMSearchGamesDidFinishedNotification object:nil];
	
	[self.searchBar cancel];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    self.searchBar = nil;
	self.searchGameList = nil;
	self.tmpGameList = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [_searchBar release];
	[_searchGameList release];
	[_tmpGameList release];
    [super dealloc];
}

#pragma mark - local method

- (void)updateGame:(NSString *)gameId isAttention:(BOOL)isAttention
{
	for (YAObjGame *game in self.gameList)
	{
		if ([game isKindOfClass:[YAObjGame class]] && [game.gameId isEqualToString:gameId])
		{
			game.isAttention = isAttention;
			break;
		}
	}
	
	NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
	[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

- (void)addAttentionNotication:(NSNotification *)notification
{
	YARespUserAttention *userAttention = [notification object];
	
	if ([userAttention.error code] == YoucApiErrorSuccess || [userAttention.error code] == YoucApiErrorAddAttentionAlreadyExists)
	{
		[self updateGame:userAttention.gameId isAttention:YES];
	}
}

- (void)deleteAttentionNotication:(NSNotification *)notification
{
	YARespUserAttention *userAttention = [notification object];
	
	if ([userAttention.error code] == YoucApiErrorSuccess)
	{
		[self updateGame:userAttention.gameId isAttention:NO];
	}
}

- (void)searchGamesNotification:(NSNotification *)notification
{
	NSDictionary *dict = notification.userInfo;
	
	LMSearchGamesParam *searchGamesParam = [dict objectForKey:LMListParamKey];
    if (self.isSearching && [searchGamesParam.searchKey isEqualToString:self.searchBar.text])
    {
        NSArray *list = [dict objectForKey:LMRESULT];
        NSError *error = [dict objectForKey:LMErrorKey];
        
		[self.searchBar finishActivity];
		
        if ([error code] == YoucApiErrorSuccess)
		{
			self.searchGameList = list;
			
			[self constructCurrentShowList];
		}
    }
}

- (void)setIsSearching:(BOOL)isSearching
{
	_isSearching = isSearching;
	
	[self enableRefreshHeader:!isSearching];
	[self enableRefreshFooter:!isSearching];
}

#pragma mark - override method

- (NSString *)gameListNotificationName
{
    return LMGetAllListDidFinishedNotification;
}

- (BOOL)loadList:(NSInteger)start limit:(NSInteger)limit
{
    LMListParam *param = [[[LMListParam alloc] init] autorelease];
    param.start = start;
    param.limit = limit;
    param.context = self;
    
    [[ListManager instance] getAllList:param forceLoad:YES];
	
	return YES;
}

- (NSArray *)getShowList
{
	NSArray *showList = nil;
	
	if (self.isSearching)
	{
		if (!self.tmpGameList)
			self.tmpGameList = self.gameList;
		self.gameList = self.searchGameList;
	}
	else if (self.tmpGameList)
	{
		self.gameList = self.tmpGameList;
		self.tmpGameList = nil;
	}
	
	showList = [super getShowList];
    
    return showList;
}

- (void)getGameListDidFinished:(NSArray *)list error:(NSError *)error
{
    [super getGameListDidFinished:list error:error];
}


#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	return self.searchBar;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 44;
}

#pragma mark - Search bar delegate methods

- (void)searchBarTextDidBeginEditing:(UISearchBar *)aSearchBar {
	[aSearchBar setShowsCancelButton:YES animated:YES];
	
	if (!self.isSearching)
	{
		self.isSearching = YES;
		
		[self constructCurrentShowList];
		
		[aSearchBar performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.1];
	}
	else
	{
		[aSearchBar becomeFirstResponder];
	}
}


- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar {

    //[aSearchBar resignFirstResponder];
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
    
    // When the search button is tapped, add the search term to recents and conduct the search.
    NSString *searchString = [aSearchBar text];
	
	LMSearchGamesParam *param = [[[LMSearchGamesParam alloc] init] autorelease];
	param.searchKey = searchString;
	[[ListManager instance] searchGames:param];
	
	[self.searchBar startActivity];
	
	[self.tableView endEditing:NO];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar
{
	aSearchBar.text = nil;
	[aSearchBar setShowsCancelButton:NO animated:YES];
	
	[self.tableView endEditing:NO];
	
	[self.searchBar finishActivity];

	if (self.isSearching)
	{
		self.isSearching = NO;
		self.searchGameList = nil;
		[self constructCurrentShowList];
	}
}

@end
